/*
* 堆场库存
* */

import 'package:center_beijing/api/statistical_analysis_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';
import 'dart:convert';

class StorageYardStock extends StatefulWidget {
  @override
  _StorageYardStockState createState() => _StorageYardStockState();
}

class _StorageYardStockState extends State<StorageYardStock>
    with SingleTickerProviderStateMixin {
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  List<SelectItems> factoriesList = [SelectItems(label: '全部仓库', value: '-1')];
  SelectItems selectFactory = SelectItems(label: '全部仓库', value: '-1');
  String selectType = '1'; //1方量  2数量
  String selectType2 = '1'; //1方量  2数量
  bool chartLoading = true;
  var charts = Map();

  EasyRefreshController _controller = EasyRefreshController();
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;

  var seriesList = '''[]''';
  var legendData =['cs','cs1'];

  @override
  void initState() {
    super.initState();
    var bbq = GlobalConfig.warehouseList;
    LogUtil.d(bbq);
    bbq.forEach((element) {
      factoriesList.add(
          SelectItems(label: element['warehouseName'], value: element['id']));
    });
    this.getChartInfo();
    this.getWarehouseInfo();
  }

  /*
  * 获取chart数据
  * */
  getChartInfo() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'radioValueChart': selectType,
      'start':Utils.timeUtil(DateTime.now().subtract(Duration(days:29)).toIso8601String()),
      'end':Utils.timeUtil(DateTime.now().toIso8601String())
    };
    var result = await getStorageChart(pass);
    if (result != null) {
      charts = result;
      seriesList = '''
        ${charts['legendData'].map((e) {
        // legendData.add("$e");
        return {'name': '\''+'$e'+'\'','type': '\''+'line'+'\'', 'areaStyle': {},'data': charts['series'][e]};
      }).toList()}
        ''';
      this.setState(() {

      });
    }
  }

  /*
  * 获取库存数据
  * */
  getWarehouseInfo() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'radioValueTable': selectType2,
      'page': page,
      'page-size': pageSize,
    };
    var result = await getStorageWarehouse(pass);
    loading.dismiss();
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null) {
      if (result.length == 0) {
      } else {
        dataSource.addAll(result);
      }
    }
    this.setState(() {});
  }

  @override
  void dispose() {
    loading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing16, Styles.spacing16, 0),
            color: Colors.white,
            child: Row(
              children: [
                Container(
                  height: 25.h,
                  width: 4.w,
                  color: Styles.BlueColor,
                  margin: EdgeInsets.only(right: Styles.spacing8),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text('实时入库曲线',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                ),
              ],
            ),
          ),
          Container(
            color: Colors.white,
            child: CustomRadio(
              top: 0,
              selectList: [
                SelectItems(label: '方量(m³)', value: '1'),
                SelectItems(label: '数量(片)', value: '2')
              ],
              selectCallback: (item) {
                this.setState(() {
                  selectType = item.value;
                  this.getChartInfo();
                });
              },
              title: '',
            ),
          ),

          Container(
            alignment: Alignment.center,
            child: Column(
              children: [
                Container(
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Echarts(
                        onLoad: (value) {
                          LogUtil.d(value);
                          this.setState(() {
                            chartLoading = false;
                          });
                        },
                        option: '''
                     {
  tooltip: {
    trigger: 'axis'
  },
  legend: {
          data: ${charts['legendData'].map((item){
            return "${'\''+item+'\''}";
                        }).toList()}
        },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ${charts['xaxisData'].map((item){
                          return json.encode(item);
                        }).toList()},
                    axisLabel: {
      fontSize:10,
      padding:[0, 0, 0, 10]
    }     
  },
  yAxis: [{
      type: 'value',
      name: '',
      axisLabel: {
        formatter: function (a) {
          a = +a
          return isFinite(a) ? echarts.format.addCommas(+a) : ''
        }
      }
    }],
  series: $seriesList
}
                  ''',
                        extraScript: '''
                    chart.on('click', (params) => {
                      if(params.componentType === 'series') {
                        Messager.postMessage(JSON.stringify({
                          type: 'select',
                          payload: params.dataIndex,
                        }));
                      }
                    });
                  ''',
                        onMessage: (String message) {
                          LogUtil.d(message);
                          // Map<String, Object> messageAction = jsonDecode(message);
                          // print(messageAction);
                          // if (messageAction['type'] == 'select') {
                          //   final item = _data1[messageAction['payload']];
                          //   _scaffoldKey.currentState.showSnackBar(
                          //     SnackBar(
                          //       content: Text(item['name'].toString() + ': ' + item['value']),
                          //       duration: Duration(seconds: 2),
                          //     ));
                          // }
                        },
                      ),
                      chartLoading
                          ? Container(
                              alignment: Alignment.center,
                              child: CircularProgressIndicator(),
                            )
                          : Container()
                    ],
                  ),
                  width: 1.sw,
                  height: 200.h,
                ),


              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: Styles.spacing8),
            padding: EdgeInsets.fromLTRB(Styles.spacing16, 0, Styles.spacing16, 0),
            color: Colors.white,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 25.h,
                  width: 4.w,
                  color: Styles.BlueColor,
                  margin: EdgeInsets.only(right: Styles.spacing8),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text('实时库存状态',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                ),
                Expanded(child: Container(
                  color: Colors.white,
                  child: CustomRadio(
                    top: 0,
                    selectList: [
                      SelectItems(label: '方量(m³)', value: '1'),
                      SelectItems(label: '数量(片)', value: '2')
                    ],
                    selectCallback: (item) {
                      this.setState(() {
                        selectType2 = item.value;
                        page=1;
                        this.getWarehouseInfo();
                      });
                    },
                    title: '',
                  ),
                ),)
              ],
            ),
          ),
          Expanded(child: Container(
            color: Styles.MainBackgroundColor,
            child: this.dataSource.length > 0
                ? EasyRefresh.custom(
                shrinkWrap: true,
                firstRefresh: false,
                controller: _controller,
                header: MaterialHeader(),
                footer: ClassicalFooter(
                    loadingText: '加载中',
                    loadText: '上拉加载',
                    noMoreText: '没有更多数据',
                    loadedText: '加载完成',
                    infoText: '更新于 %T',
                    textColor: Styles.NoMoreColor,
                    showInfo: false),
                emptyWidget: (dataSource.length == 0 && !firstLoad)
                    ? Center(
                  child: Image(
                    image: AssetImage('assets/images/no_data.png'),
                    width: 128,
                    height: 150,
                  ),
                )
                    : null,
                onRefresh: () async {
                  // _controller.finishLoad(success: true, noMore: false);
                  if (mounted) {
                    page = 1;
                    this.getWarehouseInfo();
                  }
                },
                onLoad: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    if (mounted) {
                      page++;
                      this.getWarehouseInfo();
                    }
                  });
                },
                slivers: <Widget>[
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                          (context, index) {
                        return Container(
                          color: Colors.white,
                          margin: EdgeInsets.only(bottom: Styles.spacing8),
                          padding:
                          EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing16, Styles.spacing16, Styles.spacing16),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    child: Text("${this.dataSource[index]['warehouse']}",style: TextStyle(color: Styles.DetailColor,fontSize: Styles.Middle16Font,fontWeight: Styles.FontMainWeight),),
                                  ),
                                  Container(
                                    child: Text("${this.dataSource[index]['total']}",style: TextStyle(color: Styles.BlueColor,fontSize: Styles.Middle16Font),),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.only(top: Styles.spacing8),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Container(
                                      child: Text("正常:${this.dataSource[index]['normal']}",style: TextStyle(color: Styles.LeftTitleColor,fontSize: Styles.NormalFont),),
                                    ),
                                    Container(
                                      child: Text("维修:${this.dataSource[index]['maintain']}",style: TextStyle(color: Styles.LeftTitleColor,fontSize: Styles.NormalFont),),
                                    ),

                                  ],
                                ),
                              ),


                            ],
                          ),
                        );
                      },
                      childCount: dataSource.length,
                    ),
                  ),
                ])
                : firstLoad
                ? Center(
              child: CircularProgressIndicator(),
            )
                : Center(
              child: Image(
                image: AssetImage('assets/images/no_data.png'),
                width: 128,
                height: 150,
              ),
            ),
          ))
        ],
      ),
    );
  }
}
